# Installs the latest supported Microsoft Visual C++ Redistributable.
# On 64-bit Windows, this installs both x64 and x86 because many 32-bit apps still require the x86 runtime.
# On 32-bit Windows, this installs only x86.

$ErrorActionPreference = 'Stop'

Write-Output "Detected PowerShell process architecture: $env:PROCESSOR_ARCHITECTURE"
Write-Output "Detected OS is 64-bit: $([Environment]::Is64BitOperatingSystem)"

# Microsoft latest-supported VC++ v14 Redistributable permalink URLs
$Installers = @()

if ([Environment]::Is64BitOperatingSystem) {
    $Installers += @{
        Name = 'Visual C++ Redistributable x64'
        Url  = 'https://aka.ms/vc14/vc_redist.x64.exe'
        Path = Join-Path $env:TEMP 'vc_redist.x64.exe'
    }

    $Installers += @{
        Name = 'Visual C++ Redistributable x86'
        Url  = 'https://aka.ms/vc14/vc_redist.x86.exe'
        Path = Join-Path $env:TEMP 'vc_redist.x86.exe'
    }
}
else {
    $Installers += @{
        Name = 'Visual C++ Redistributable x86'
        Url  = 'https://aka.ms/vc14/vc_redist.x86.exe'
        Path = Join-Path $env:TEMP 'vc_redist.x86.exe'
    }
}

foreach ($Installer in $Installers) {
    Write-Output "Downloading $($Installer.Name) from $($Installer.Url)"

    Invoke-WebRequest `
        -Uri $Installer.Url `
        -OutFile $Installer.Path `
        -UseBasicParsing

    Write-Output "Installing $($Installer.Name)"

    $Process = Start-Process `
        -FilePath $Installer.Path `
        -ArgumentList '/install', '/quiet', '/norestart' `
        -Wait `
        -PassThru

    Write-Output "$($Installer.Name) installer exit code: $($Process.ExitCode)"

    # 0 = success
    # 3010 = success, reboot required
    if ($Process.ExitCode -notin @(0, 3010)) {
        throw "$($Installer.Name) failed with exit code $($Process.ExitCode)"
    }

    Remove-Item -Path $Installer.Path -Force -ErrorAction SilentlyContinue
}

Write-Output 'Visual C++ Redistributable installation completed successfully.'